package cc.edge2.sns.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.arnx.jsonic.JSON;
import cc.edge2.sns.commons.PMF;
import cc.edge2.sns.models.Diary;
import cc.edge2.sns.models.FriendRelation;
import cc.edge2.sns.models.RecentFriendDiary;
import cc.edge2.sns.models.SNSUser;

import com.google.appengine.api.datastore.Text;

public class SaveDiaryService {
	public String execute(Map params, SNSUser user) {
		Diary diary = new Diary(user.getUserId(), (String)params.get("subject"), ((String)params.get("body")), new Date());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(FriendRelation.class);
		try { 
			diary = pm.makePersistent(diary);
			long diaryId = diary.getDiaryId();
			query.setFilter("userId1 == :userId1Param");
			long userId = user.getUserId();
			List<RecentFriendDiary> list = new ArrayList<RecentFriendDiary>();
			List<FriendRelation> results = (List<FriendRelation>)query.execute(userId);
			for(FriendRelation friendRelation : results) {
				long friendUserId = friendRelation.getUserId2();
				RecentFriendDiary recentFriendDiary = new RecentFriendDiary(friendUserId, diaryId);
				list.add(recentFriendDiary);
			}
			pm.makePersistentAll(list);
		} finally {
			query.closeAll();
			pm.close();
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> contents = new HashMap<String, Object>();
		Map<String, Object> status = new HashMap<String, Object>();
		status.put("code", "0");
		status.put("message", "success");
		result.put("status", status);
		result.put("contents", contents);
		contents.put("body", diary.getBody().toString());
		String value = JSON.encode(result);
		return value;
	}
}
